import os
import sys
from pathlib import Path
from natsort import natsorted
# https://pypi.org/project/jpg2pdf/
import jpg2pdf
from time import perf_counter


def get_ext(file_name):
    split_tup = os.path.splitext(file_name)
    return split_tup[1]


def convert_folders_images(images_folder, pdfs_folder):
    t1 = perf_counter()
    images_folder_posix = Path(images_folder).as_posix()
    pdfs_folder_posix = Path(pdfs_folder).as_posix()
    for (dirpath, dirnames, filenames) in os.walk(images_folder):
        if not any(n for n in filenames if get_ext(n) == '.jpg'):
            continue
        dir_path = Path(dirpath)
        src_pdf_file = dir_path.parent / (dir_path.name + '.pdf')
        pdf_file = src_pdf_file.as_posix().replace(images_folder_posix, pdfs_folder_posix)
        if os.path.isfile(pdf_file):
            # sys.stdout.write('.')
            # sys.stdout.flush()
            continue
        try:
            os.makedirs(Path(pdf_file).parent, exist_ok=True)
            with jpg2pdf.create(pdf_file) as pdf:
                for name in natsorted(filenames):
                    pdf.add(dir_path / name)
                print(pdf_file)
            print(pdf_file)
        except Exception as e:
            print(f'{dir_path} {str(e)}')
            continue
    t2 = perf_counter()
    print(t2 - t1)


if __name__ == '__main__':
    images_folder = r'C:\Users\yang.lei\Downloads\测试文件\A路径'
    pdfs_folder = r'C:\Users\yang.lei\Downloads\测试文件\B路径'
    convert_folders_images(images_folder, pdfs_folder)
